/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.hutech09.jsale.web.manager.category;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import org.hutech09.jsale.bsn.ICategoryManager;
import org.hutech09.jsale.bsn.exception.ItemExistsException;
import org.hutech09.jsale.entity.Category;

/**
 *
 * @author Nam
 */
@ManagedBean
@RequestScoped
public class CategoryCuCtrl {

    @EJB
    private ICategoryManager cm;
    
    @ManagedProperty("#{categoryBrowseCtrl}")
    private CategoryBrowseCtrl browse;

    private Category category;

    private String afterApplyPage;

    private String aCategoryName;
    
    public CategoryCuCtrl() {
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    public String showUpdate(Category category, String afterApplyPage) {
        this.category = category;
        this.afterApplyPage = afterApplyPage;
        return "categoryEditPage";
    }
    
    public String showCreate(String afterApplyPage){
        this.afterApplyPage = afterApplyPage;
        return "categoryCreatePage";
    }

    public String create() {
        cm.create(category);
        return afterApplyPage;
    }

    public String update() {
        try {
            cm.update(category);
        } catch (ItemExistsException ex) {
            Logger.getLogger(CategoryCuCtrl.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
        return afterApplyPage;
    }

    public void aCreateCategory(){
        Category c = new Category();
        c.setName(aCategoryName);
        aCategoryName = "";
        cm.create(c);
        browse.init();
    }
    
    public void aUpdateCategory(){
        Category c = browse.getSelectedCategory();
        if(c!=null){
            c.setName(aCategoryName);
            try {
                cm.update(c);
            } catch (ItemExistsException ex) {
                Logger.getLogger(CategoryCuCtrl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public String getACategoryName() {
        return aCategoryName;
    }

    public void setACategoryName(String aCategoryName) {
        this.aCategoryName = aCategoryName;
    }

    public CategoryBrowseCtrl getBrowse() {
        return browse;
    }

    public void setBrowse(CategoryBrowseCtrl browse) {
        this.browse = browse;
    }
    
}
